﻿using Repid.Core.Aop;
using Repid.MvcExtension.Controllers;
using Repid.Utility.Helper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Repid.MvcApplication.Areas.Other.Controllers
{
    /// <summary>
    /// 通用管理
    /// </summary>
    public class CommonController : Controller
    {
        public void Upload(string imgDir)
        {
            string path = ConfigHelper.FilePath + imgDir;

            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            if (Request.Files.Count > 0)
            {
                try
                {
                    HttpPostedFileBase file = HttpContext.Request.Files.Get(0);

                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;

                    file.SaveAs(path + fileName);

                    Response.Write(JsonHelper.Serialize(new { success = true, file = fileName }));
                }
                catch (Exception ex)
                {
                    LogHelper.Error(this, ex); throw ex;
                }
            }
            else { throw new Exception("未找到文件！"); }
        }

        public void UploadCut(string imgDir, int width, int height)
        {
            string temp = ConfigHelper.FilePath + "\\temp";
            string path = ConfigHelper.FilePath + imgDir;

            if (!Directory.Exists(temp)) { Directory.CreateDirectory(temp); }
            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            if (Request.Files.Count > 0)
            {
                try
                {
                    HttpPostedFileBase file = HttpContext.Request.Files.Get(0);

                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    string tempFile = temp + "\\" + Guid.NewGuid() + fileExt;
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;

                    file.SaveAs(tempFile);

                    ThumbnailHelper.Generate(tempFile, path + fileName, width, height, TnType.Cut);

                    System.IO.File.Delete(tempFile);

                    Response.Write(JsonHelper.Serialize(new { success = true, file = fileName }));
                }
                catch (Exception ex)
                {
                    LogHelper.Error(this, ex); throw ex;
                }
            }
            else { throw new Exception("未找到文件！"); }
        }
    }
}